<template>
  <header class="app-header">
    <div class="logo">图书馆管理系统</div>
    <div class="user-info" v-if="user">
      <img 
        :src="user.avatar ? `http://localhost:8082/avatars/${user.avatar}` : '/default-avatar.png'"
        :alt="user.username" 
        class="avatar"
        @error="handleAvatarError"
      >
      <span class="username">{{ user.username }}</span>
    </div>
    <div class="auth-buttons" v-else>
      <router-link to="/login" class="btn-login">登录</router-link>
      <router-link to="/register" class="btn-register">注册</router-link>
    </div>
  </header>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const user = ref(null);

onMounted(() => {
    // 从localStorage获取用户信息
    try {
      const storedUser = localStorage.getItem('user');
      if (storedUser && storedUser !== 'undefined') {
        user.value = JSON.parse(storedUser);
      }
    } catch (error) {
      console.error('Failed to parse user data from localStorage:', error);
      // 清除无效数据
      localStorage.removeItem('user');
    }
  });

const handleAvatarError = (e) => {
  // 头像加载失败时使用默认头像
  e.target.src = '/default-avatar.png';
};
</script>

<style scoped>
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.username {
  font-size: 14px;
  color: #666;
}

.auth-buttons {
  display: flex;
  gap: 10px;
}

.btn-login,
.btn-register {
  padding: 6px 12px;
  text-decoration: none;
  border-radius: 4px;
  font-size: 14px;
}

.btn-login {
  color: #666;
  background-color: #f5f5f5;
}

.btn-register {
  color: #fff;
  background-color: #409eff;
}
</style>